# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-07-15 23:17
# File     : marketstack_adapter.py
# Project  : dynamic-portfolio-optimizer
# Desc     :
# src/data/adapters/marketstack_adapter.py
import requests
from typing import Dict, List, Any
import pandas as pd
from datetime import datetime
from .base_adapter import BaseDataAdapter, RateLimitDecorator


class MarketstackAdapter(BaseDataAdapter):
    """Marketstack数据适配器"""

    def __init__(self, config):
        super().__init__(config)
        self.base_url = config.base_url
        self.api_key = config.api_key

    @RateLimitDecorator(calls=10, period=60)
    def get_stock_data(self, symbol: str, start_date: datetime,
                       end_date: datetime, interval: str = '1d') -> pd.DataFrame:
        """获取股票数据"""
        try:
            # Marketstack主要支持日线数据
            url = f"{self.base_url}/v1/eod"

            params = {
                'access_key': self.api_key,
                'symbols': symbol,
                'date_from': start_date.strftime('%Y-%m-%d'),
                'date_to': end_date.strftime('%Y-%m-%d'),
                'limit': 1000
            }

            response = self.session.get(url, params=params)
            response.raise_for_status()

            data = response.json()

            if not data.get('data'):
                self.logger.warning(f"Marketstack: 未获取到{symbol}的数据")
                return pd.DataFrame()

            # 转换为DataFrame
            df_data = []
            for item in data['data']:
                df_data.append({
                    'timestamp': datetime.strptime(item['date'], '%Y-%m-%dT%H:%M:%S%z'),
                    'open': item['open'],
                    'high': item['high'],
                    'low': item['low'],
                    'close': item['close'],
                    'volume': item['volume']
                })

            df = pd.DataFrame(df_data)
            df.set_index('timestamp', inplace=True)
            df['source'] = 'marketstack'
            df['symbol'] = symbol

            return self.standardize_data(df)

        except Exception as e:
            self.logger.error(f"Marketstack获取股票数据失败: {e}")
            return pd.DataFrame()

    def get_options_data(self, symbol: str, expiration_date: datetime) -> pd.DataFrame:
        """获取期权数据 (Marketstack不支持期权数据)"""
        self.logger.info("Marketstack不支持期权数据")
        return pd.DataFrame()

    def get_fundamentals(self, symbol: str) -> Dict[str, Any]:
        """获取基本面数据 (Marketstack不支持基本面数据)"""
        self.logger.info("Marketstack不支持基本面数据")
        return {}

    def get_news(self, symbol: str, limit: int = 10) -> List[Dict[str, Any]]:
        """获取新闻数据 (Marketstack不支持新闻数据)"""
        self.logger.info("Marketstack不支持新闻数据")
        return []

